﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TrafficArchives.Common;
using TrafficArchives.DataAccess;
using TrafficArchives.Logs;
using TrafficArchives.Models;

namespace TrafficArchives.Users
{
    public partial class AddUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Initlize();
            }
        }

        private void Initlize()
        {
            var condition = new Condition(ConditionRelation.And, "isvalis", ConditionOperator.Equal, new object[] {1});
            var rlDb = new RoleDb();
            var rlData = rlDb.GetData(new Request{Items = new List<Condition>{condition}}).Data;
            rlData.PrimaryKey = new[] { rlData.Columns["userrole_id"] };
            DdlRole.DataSource = rlData;
            DdlRole.DataTextField = "rolename";
            DdlRole.DataValueField = "userrole_id";
            DdlRole.DataBind();

            var dpDb = new DepartmentDb();
            var dpData = dpDb.GetData();
            DdlManageOrgan.DataSource = dpData;
            DdlManageOrgan.DataTextField = "treepath";
            DdlManageOrgan.DataValueField = "id";
            DdlManageOrgan.DataBind();

            var item = new ListItem("<请选择>", "");
            DdlRole.Items.Insert(0, item);

            if (Request.QueryString["action"] == "edit"
                && !string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                LblTitle.InnerText = "修改用户";
                var id = Request.QueryString["id"];
                var db = new UserDb();
                var data = db.GetData(id);
                if (data.Rows.Count > 0)
                {
                    var roleId = data.Rows[0]["userrole_id"].ToString();
                    if (rlData.Rows.Find(roleId) != null)
                    {
                        DdlRole.SelectedValue = roleId;
                    }
                    var departmentId = data.Rows[0]["GLBM_ID"].ToString();
                    if (dpData.Rows.Find(departmentId) != null)
                    {
                        DdlManageOrgan.SelectedValue = departmentId;
                    }
                    TxtUserCode.Text = data.Rows[0]["USERCODE"].ToString();
                    TxtUserName.Text = data.Rows[0]["USERNAME"].ToString();
                    TxtPassword.Attributes.Add("value","-1");
                    TxtConfrimPassword.Attributes.Add("value", "-1");
                }
            }
            else
            {
                DdlManageOrgan.SelectedIndex = 0;
                DdlRole.SelectedIndex = 0;
                LblTitle.InnerText = "添加用户";
                TxtPassword.Attributes.Add("value", "888888");
                TxtConfrimPassword.Attributes.Add("value", "888888");
            }
            
        }

        protected void  ValidateUserCode(object source, ServerValidateEventArgs args)
        {
            if (String.IsNullOrEmpty(Request.QueryString["action"])
                || Request.QueryString["action"] != "edit")
            {
                args.IsValid = new UserDb().IsUnique(TxtUserCode.Text);
                TxtUserCodeValidator.Visible = args.IsValid;
                UpdatePanelForm.Update();
            }
        }

        protected void BtnSaveClick(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }
            var db = new UserDb();
            var isEdit = Request.QueryString["action"] == "edit" && !string.IsNullOrEmpty(Request.QueryString["id"]);
            var data = isEdit ? db.GetData(Request.QueryString["id"]) : db.GetNoneData();

            if (!isEdit)
            {
                var newRow = data.NewRow();
                newRow["USER_ID"] = Guid.NewGuid().ToString();
                data.Rows.Add(newRow);
            }
            data.Rows[0]["userrole_id"] = DdlRole.SelectedValue;
            data.Rows[0]["USERCODE"] = TxtUserCode.Text;
            data.Rows[0]["USERNAME"] = TxtUserName.Text;
            
            if (TxtPassword.Text != "-1")
            {
                data.Rows[0]["USERPASSWORD"] = Md5.Encrypt(TxtPassword.Text);
            }
            
            if (isEdit)
            {
                db.Update(data);
                var log = new LogInfo(LogType.用户信息修改);
                LogWriter.Writer(log);
            }
            else
            {
                db.Add(data);
                var log = new LogInfo(LogType.用户信息添加);
                LogWriter.Writer(log);
            }
            Response.Redirect("UserView.aspx");
        }
    }
}